<?php
/**
 * RedCross Application
 *
 * @copyright Copyright (c) 2010, Kristian Stokke Tryggestad, Rune Vikestad, Andreas Flaten Wist, Simen Nicolai Echholt, Ole Henrik Jahren
 */


class Core_Service_User extends RedCross_Service_ServiceAbstract
{

    public function __construct(Core_Gateway_User $gateway)
    {
        parent::__construct($gateway, 'Core_Model_User');
    }

    public function getValidator()
    {
        return new Core_Form_User_Login();
    }

    public function create(array $data)
    {
        $this->checkAcl('create');

        $memberGateway = $this->getGateway('Core_Gateway_Member');
        $member = $memberGateway->fetchByEmail($data['email']);
        $member->is_public = $data['is_public'];
        $member->save();

        $data['member_id'] = $member['id'];
        unset($data['email']);

        $user = new Core_Model_User();
        $data['salt'] = Core_Model_User::createSalt();
        $data['password'] = $user->hashPassword($data['password'], $data['salt']);
        $user->fromArray($data);

        return $this->save($user);
    }

    public function deleteUser($userId)
    {
        $this->checkAcl('delete');
		return $this->getGateway()->deleteUser($userId);
    }

    public function confirmUser($userId)
    {
        $this->checkAcl('confirm');
    	$user = $this->fetch($userId);
        if (!is_object($user))
        {
        	throw new RedCross_Exception_NotFound('Angitt bruker ikke funnet');
        }

        $user->is_confirmed = 1;

        $config = Zend_Registry::get('config');
        $user->UserGroup[]->group_id = $config['user']['default']['group'];

        return $this->save($user) != false;
    }    
    
    public function changePassword($userId, $password)
    {
        $user = $this->fetchById($userId);
        $user->salt = Core_Model_User::createSalt();
        $user->password = $user->hashPassword($password, $user->salt);
        return $this->save($user);
    }

    public function fetchById($id)
    {
        return $this->getGateway()->fetchById($id);
    }

    /**
     * @deprecated
     */
    public function fetchUsersAndMemberNames()
    {
    	return $this->getGateway()->fetchUsersAndMemberNames();
    }

    public function fetchUsersAll($paginate = false)
    {
        $this->checkAcl('fetchAll');
        return $this->getGateway()->fetchUsersAll($paginate);
    }

    public function fetchUsersOnlyConfirmed($paginate = false)
    {
        $this->checkAcl('fetchAll');
        return $this->getGateway()->fetchUsersOnlyConfirmed($paginate);
    }
    
    public function fetchUsersOnlyUnconfirmed($paginate = false)
    {
        $this->checkAcl('fetchAll');
        return $this->getGateway()->fetchUsersOnlyUnconfirmed($paginate);
    }

    public function fetchByIdForProfile($userId) {
		return $this->getGateway()->fetchByIdIncludingMemberRelations($userId);
    }
}
